//
//  NweFeatureCollectionViewController.swift
//  xinlangweibo
//
//  Created by yangshuo on 15/12/2.
//  Copyright © 2015年 yangshuo. All rights reserved.
//

import UIKit
import SnapKit
private let WBNewFeatureReuseIdentifier = "Cell"
        let NewFeatureImageCount = 4

class NewFeatureCollectionViewController: UICollectionViewController {
    //注意superinit中不能使用懒加载,懒加载属性必须要在控制器实例化才会创建,而super.init中对象是一下子就创建出来
  //  private lazy var layout = UICollectionViewFlowLayout()
     //构造函数,方便外部调用
    init(){
        //super指定的构造函数
          //实例化一个布局对象
        let layout = UICollectionViewFlowLayout()
        //collectionView布局设置
        //图像大小
        layout.itemSize = UIScreen.mainScreen().bounds.size
        //最小格子间距
        layout.minimumInteritemSpacing = 0
        //最小行间距
        layout.minimumLineSpacing = 0
        //滚动方向
        layout.scrollDirection = .Horizontal
        
        //调用它的构造函数
        //connectionView控件设置必须写在super.init下面
        //因为super.init之后控件(内部属性)才会被创建(实例化)
        super.init(collectionViewLayout: layout)
        //开启分页
        collectionView?.pagingEnabled = true
        //取消回弹
        collectionView?.bounces = false
        //取消滚动条
        collectionView?.showsHorizontalScrollIndicator = false
        

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //隐藏状态栏
    override func prefersStatusBarHidden() -> Bool {
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: WBNewFeatureReuseIdentifier)

        // Do any additional setup after loading the view.
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return NewFeatureImageCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WBNewFeatureReuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell//将cell as成自定义的cell
    
        cell.imageIndex = indexPath.item
        
        return cell
    }
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        //collectionview继承自scrollview
        //这里的scrollview参数其实就是collectionview
        //获取总页数=scrollView.x的偏移量/scrollview.width
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        //判断当前页数是否为最后一页
        if page != NewFeatureImageCount - 1{
            return
        }
        //cell播放动画(cell显示为最后一页NSIndexpath,并将该cell类型转换为NewFeatureCell)
        let cell = collectionView?.cellForItemAtIndexPath(NSIndexPath(forItem: page, inSection: 0)) as! NewFeatureCell
        //播放动画
        cell.showButtonAnimation()
    }

//MARK: -新特性cell
    private class NewFeatureCell: UICollectionViewCell{
        //设置图像属性
        private var imageIndex: Int = 0{
            didSet{
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
                //将按钮隐藏
       startButton.hidden = true
            }
        }
        //UIview的指定构造函数格式
       override init(frame: CGRect) {
            //这里的frame大小是itemSize指定的
            super.init(frame: frame)

           setupUI()
        }
        //实现按钮监听事件
        @objc private func clickStartButton(){
             NSNotificationCenter.defaultCenter().postNotificationName(WBSwithchRootControllerNotification, //通知的名称,用来给监听中心识别通知
                object: nil)//传递给通知中心的一个参数,与监听对象的object不一样
        }
        
        
        
        
       required init?(coder aDecoder: NSCoder) {
           fatalError("init(coder:) has not been implemented")
       }

        private func showButtonAnimation(){
            //显示按钮
            startButton.hidden = false
            //禁止交互
            startButton.userInteractionEnabled = false
            startButton.transform = CGAffineTransformMakeScale(0, 0)
            UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 10.0, options: [], animations: { () -> Void in
                //闭包需要self
                self.startButton.transform = CGAffineTransformIdentity
                }) { (_) -> Void in
                    //动画结束允许交互
                self.startButton.userInteractionEnabled = true
   
            }
        }
        private func setupUI(){
            //添加控件
            addSubview(iconView)
            addSubview(startButton)
            //指定位置
            iconView.frame = bounds//0.0
            //设置按钮约束
            startButton .snp_makeConstraints { (make) -> Void in
                make.centerX.equalTo(iconView.snp_centerX)
                make.centerY.equalTo(iconView.snp_centerY).multipliedBy(1.6)
            }
            //注意按钮隐藏不能设置setup这里,因为在collection中cell具有重用机制,虽然有四个页面,但实际上只有2个cell.会导致该按钮在额外的页面上显示.
           // startButton.hidden = true
      //添加按钮监听事件
            startButton.addTarget(self, action: "clickStartButton", forControlEvents: .TouchUpInside)
            
        }
        //懒加载cell控件
        private lazy var iconView: UIImageView = UIImageView()
        //懒加载按钮
        private lazy var startButton: UIButton = UIButton(title: "开始体验", color: UIColor.whiteColor(), backImageName: "new_feature_finish_button")    }
}
